from django.shortcuts import render_to_response
from django.http import Http404, HttpResponseRedirect
from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
from utils.urlresolvers import locreverse

from myapps.polls import models
from myapps.polls import forms

@csrf_protect
def vote_f(request, poll_id):
    poll_id = int(poll_id)
    poll = models.Poll.get_by_id(poll_id)
    if poll is None:
        raise Http404
    
    VoteForm = forms.vote_ff(poll)
    
    return render_to_response('polls/vote_f.html',
        {'form': VoteForm(),
         'poll': poll},
        context_instance=RequestContext(request))


@csrf_protect
def vote(request, poll_id):
    poll_id_u, poll_id = poll_id, int(poll_id)
    
    poll = models.Poll.get_by_id(poll_id)
    if poll is None:
        raise Http404
    
    VoteForm = forms.vote_ff(poll)
    form = VoteForm(request.POST)
    if form.is_valid():
        # Get data
        choice_id = form.cleaned_data['choice']
        # Vote
        models.Poll.vote(poll_id, choice_id)
        
        return HttpResponseRedirect(locreverse('polls-results', args=(poll_id_u,)))
    else:
        return render_to_response('polls/vote_f.html',
            {'form': form,
             'poll': poll},
            context_instance=RequestContext(request))
